<?php
/**
 * Created by PhpStorm
 * User: lcz
 * Date: 2019/10/8
 * Time: 11:42
 * 队列任务
 */

namespace app\common\controller;

use app\admin\model\User;
use app\common\library\Redis;
use app\common\model\Commission;
use app\common\model\Funds;
use app\common\model\History;
use app\common\model\Order;
use app\common\model\QueueError;
use app\common\model\RecommendRebate;
use app\common\model\UserSale;
use think\Controller;
use think\Db;
use think\Exception;

class Queue extends Controller
{
	
	/**
	 * 添加用户关系
	 */
	public function addUserLayer($data)
	{
		$userId = $data['user_id'];
		$parentId = $data['parent_id'];
		
		
		
		
		$parents = Db::name('userLayer')
			->where(['user_id' => $parentId])
			->field('parent_id, layer + 1 as layer,' . time() . ' as create_time, '.$userId.' as user_id, ' . time() . ' as update_time')
			->order(['layer' => 'asc'])
			->select();
		
		!$parents && $parents = [];
		
		$parents[] = [
			'parent_id' => $parentId,
			'layer' => 1,
			'create_time' => time(),
			'user_id' => $userId,
			'update_time' => time()
		];
		
		
		
		$res = Db::name('userLayer')->insertAll($parents);
		if($res) {
			return '添加推荐关系成功';
		} else {
			$this->addError('addUserLayer', $data, '添加用户关系');
			return '添加推荐关系失败';
		}
	}
	
	
	/**
	 * 添加用户浏览记录
	 */
	public function addHistory($data)
	{
		$model = new History();
		$row = $model->where($data)->find();
		if ($row) {
			$res = $model->save([
				'number' => $row['number'] + 1,
				'status' => 1
			], $data);
		} else {
			$res = $model->isUpdate(false)
				->save($data);
		}
		
		if($res) {
			return '添加用户浏览记录成功';
		} else {
			$this->addError('addHistory', $data, '添加用户浏览记录');
			return '添加用户浏览记录失败';
		}
	}
	
	/**
	 * 订单支付成功后的操作
	 * @param $data
	 */
	public function orderPaySuccess($data) {
		$orderId = $data['id'];
		$goods = Db::name('orderGoods')
			->where(['order_id' => $orderId])
			->select();
		//开通的会员等级
		$level = 0;
		
		$order = Order::get($orderId);
		
		$parents = Db::name('userLayer')->alias('l')
			->join('user u', 'l.parent_id = u.id', 'left')
			->where(['l.user_id' => $order['user_id']])
			->order('l.layer asc')
			->field('l.layer, l.parent_id as user_id, u.level')
			->select();
		
		$commissionModel = new Commission();
		$saleModel = new UserSale();
		
		$goodsId = $goods[0]['goods_id'];
		$orderGoodsId = $goods[0]['id'];
		
		$user = \app\common\model\User::get($order['user_id']);
		
		$saleModel->startTrans();
		try {
			$task = [];
			foreach ($goods as $good) {
				//商品信息
				$goodsInfo = json_decode($good['goods_info'], true);
				
				//返利配置
				$rebateInfo = json_decode($good['rebate_info'], true);
				
				//记录添加的最大开通会员等级
				if($goodsInfo['open_level'] > $level) {
					$level = $goodsInfo['open_level'];
					$goodsId = $good['goods_id'];
					$orderGoodsId = $good['id'];
				}
				
				//添加商品购买数量
				$numRes = Db::name('goods')
					->where(['id' => $good['goods_id']])
					->setInc('number_sale', $good['number']);
				if($numRes === false) {
					throw new Exception('添加商品ID【'.$good['goods_id'].'】购买数量出错');
				}
				
				//直接推荐人返利
				if(isset($parents[0]) && $rebateInfo['pid'] > 0) {
					$pUser = $parents[0];
					$pRes = $commissionModel->rebate($pUser['user_id'], $order['user_id'], $orderId, $good['goods_id'], $good['id'], $rebateInfo['pid']*$good['number'], '下级订单返利');
					if(!$pRes) {
						throw new Exception('下级订单返利'.$commissionModel->getError());
					}
				}
				
				//间接推荐人返利
				if(isset($parents[1]) && $rebateInfo['ppid'] > 0) {
					$ppUser = $parents[1];
					$ppRes = $commissionModel->rebate($ppUser['user_id'], $order['user_id'], $orderId, $good['goods_id'], $good['id'], $rebateInfo['ppid']*$good['number'], '间接下级订单返利');
					if(!$ppRes) {
						throw new Exception('间接下级订单返利'.$commissionModel->getError());
					}
					
					
				}
				
				$agents = array_merge([['user_id' => $order['user_id'], 'level' => $user['level']]], $parents);
				//代理返利
				$agentRebateRes = $commissionModel->agentRebate($agents, $rebateInfo,$order['user_id'], $orderId, $good['goods_id'], $good['id'], $good['number']);
				
				if(!$agentRebateRes) {
					throw new Exception('代理返利出错'.$commissionModel->getError());
				}
				
				//记录升级数量
				
				if($goodsInfo['is_join_upgrade'] == 1) {
					$levelRes = $saleModel->addNumber($order['user_id'], $parents, $good['number']);
					
					if(!$levelRes) {
						throw new Exception('添加升级数量出错'.$saleModel->getError());
					}
					
					$task = array_merge($task, $levelRes);
				}
				
			}
			
			//开通用户等级
			$user = User::get($order['user_id']);
			if($user['level'] < $level) {
				$levelRes = Db::name('user')->where(['id' => $order['user_id']])->update(['level' => $level]);
				if(!$levelRes) {
					throw new Exception('更改购买用户等级出错');
				}
				
				//新开通会员的给推荐人奖励
//				if($user['level'] == 0) {
//					$recommendRule = Db::name('recommendRebate')->find();
//					if($recommendRule) {
//						$recommendModel = new RecommendRebate();
//
//						//直接推荐人返利
//						if(isset($parents[0])) {
//							$pUser = $parents[0];
//							//获取直接推荐人对应等级的推荐奖励
//							$pAmount = $recommendModel->getPidAmount($recommendRule, $pUser['level']);
//							if($pAmount > 0) {
//								$pRes = $commissionModel->rebate($pUser['user_id'], $order['user_id'], $orderId, $goodsId, $orderGoodsId, $pAmount, '直接推荐人返利');
//
//								if(!$pRes) {
//									throw new Exception('直接推荐人'.$commissionModel->getError());
//								}
//
//							}
//						}
//
//						//间接推荐人返利
//						if(isset($parents[1])) {
//							$ppUser = $parents[1];
//							$ppAmount = $recommendModel->getPidAmount($recommendRule, $ppUser['level'], 'pp_');
//							if($ppAmount > 0) {
//								$ppRes = $commissionModel->rebate($ppUser['user_id'], $order['user_id'], $orderId, $goodsId, $orderGoodsId, $ppAmount, '间接推荐人返利');
//								if(!$ppRes) {
//									throw new Exception('间接推荐人'.$commissionModel->getError());
//								}
//							}
//						}
//					}
//				}
			}
			
			
			
			$saleModel->commit();
			
			$status = true;
			
			if($task) {
				foreach ($task as $item) {
					self::addTask($item['method'], $item['data']);
				}
			}
	 	} catch (Exception $e) {
			$saleModel->rollback();
			$status = false;
		}
		
		
		if($status) {
			return '订单操作成功';
		} else {
			$this->addError('orderPaySuccess', $data, '订单操作');
			return '订单操作出错';
		}
		
	}
	
	/**
	 * 添加执行错误的记录到数据库
	 * @param $method
	 * @param $data
	 * @param $name
	 */
	public function addError($method, $data, $name) {
		$model = new QueueError();
		$model->isUpdate(false)
			->save([
				'method' => $method,
				'data' => $data,
				'name' => $name
			]);
	}
	
	/**
	 * 添加队列任务
	 * @param $method
	 * @param $data
	 */
	public static function addTask($method, $data)
	{
		$redis = Redis::getInstance();
		$config = config('redis');
		$res = $redis->rPush($config['prefix'] . $config['name']['queue'], json_encode([
			'method' => $method,
			'data' => $data
		]));
		return $res;
	}
	
	/**
	 * 身份升级
	 */
	public function checkLevel($data) {
		$userId = $data['user_id'];
		$user = \app\common\model\User::get($userId);
		$level = $user['level'] + 1;
		
		$setting = Db::name('levelSetting')
			->where(['level' => $level])
			->find();
		if(!$setting) {
			return '没有相关升级配置';
		}
		
		$row = Db::name('userSale')
			->where(['user_id' => $userId])
			->find();
		
		if($row && ($row['self_number'] >= $setting['self_number'] || $row['team_number'] >= $setting['team_number'])) {
			
			$res = Db::name('user')->where(['id' => $userId])->update(['level' => $level]);
			if($res) {
				return '升级成功';
			} else {
				$this->addError('checkLevel', $data, '身份升级');
				return '升级出错';
			}
		} else {
			return '未满足升级条件';
		}
		
	}
}
